package component

import (
	"errors"
	"fmt"
	"github.com/spf13/viper"
	"os"
	"path/filepath"
)

var ConfigObj *viper.Viper
var ConfigModel ConfigS

type ImServerConfig struct {
	Type string
	Uni  string
	Port string
}

type HttpServerConfig struct {
	Port string
}

type MysqlConfig struct {
	User   string
	Pwd    string
	Host   string
	Port   int
	DbName string `mapstructure:"db_name"`
}

type LogConfig struct {
	LogRoot       string `mapstructure:"log_root"`
	LogPath       string `mapstructure:"log_path"`
	DefaultLog    string `mapstructure:"default_log"`
	ConsoleOutput bool   `mapstructure:"console_output"`
}

type ConfigS struct {
	Mode       string
	RpcPort    int              `mapstructure:"rpc_port"`
	HttpServer HttpServerConfig `mapstructure:"http_server"`
	ImServers  []ImServerConfig `mapstructure:"im_servers"`
	Mysql      MysqlConfig
	Log        LogConfig
}

func loadConfig() {
	config := viper.New()
	//设置读取的文件路径
	configPath := filepath.Join(rootPath, "config")
	fmt.Println(configPath)
	if _, err := os.Stat(configPath); os.IsNotExist(err) {
		panic(errors.New("no config dir"))
	}
	//设置读取的文件路径
	config.AddConfigPath(configPath)
	config.SetConfigName("main")
	config.SetConfigType("yaml") //设置文件的类型
	if err := config.ReadInConfig(); err != nil {
		panic(fmt.Errorf("load config err %w", err))
	}
	ConfigObj = config
	var c ConfigS
	err := ConfigObj.Unmarshal(&c)
	if err != nil {
		panic(fmt.Errorf("read config err %w", err))
	}
	ConfigModel = c

	fmt.Println("-->加载config完成")
}
